// https://gitee.com/ZiChenMuFeng/manager-server
const Koa = require('koa');
const app = new Koa();
// 参数json化
const json = require('koa-json');
// 错误监听
const onerror = require('koa-onerror');
// 请求解析
const bodyparser = require('koa-bodyparser');
// 跨域
const cors = require('koa2-cors');
const koajwt = require('koa-jwt');

const config = require('./config/index');
const log4js = require('./utils/logger');
const util = require('./utils/util');
// 数据库连接
require('./db');
const appRouter = require('koa-router')();
const userRoute = require('./routes/user');
const menuRoute = require('./routes/menu');
const roleRoute = require('./routes/role');
const deptRoute = require('./routes/dept');
const leaveRoute = require('./routes/leave');

// error handler
onerror(app);

// middlewares
app.use(cors());
app.use(bodyparser({ enableTypes: ['json', 'form', 'text'] }));
app.use(json());
// 静态目录
app.use(require('koa-static')(__dirname + '/public'));

// logger
app.use(async (ctx, next) => {
  let { method, url, query, body } = ctx.request;
  let content = method.toLowerCase() === 'get' ? JSON.stringify(query) : JSON.stringify(body);
  log4js.info(`${method} --> ${url} --> params:${content}`);
  await next().catch((err) => {
    // token 认证失败
    if (err.status == '401') {
      ctx.status = 200;
      ctx.body = util.failAuth();
    } else {
      throw err;
    }
  });
});

// koa-jwt
app.use(koajwt({ secret: config.jwtKey }).unless({ path: [/^\/api\/user\/login/] }));

// routes
appRouter.prefix('/api');
appRouter.use(userRoute.routes(), userRoute.allowedMethods());
appRouter.use(menuRoute.routes(), menuRoute.allowedMethods());
appRouter.use(roleRoute.routes(), roleRoute.allowedMethods());
appRouter.use(deptRoute.routes(), deptRoute.allowedMethods());
appRouter.use(leaveRoute.routes(), leaveRoute.allowedMethods());
app.use(appRouter.routes(), appRouter.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  let { method, url } = ctx.request;
  log4js.error(`${method} --> ${url} error:${err.stack}`);
});

module.exports = app;
